using Microsoft.EntityFrameworkCore;
using RiceShop.Models;


namespace RiceShop.Services
{
    /// <summary>
    /// 购物车服务接口
    /// </summary>
    public interface ICartService
    {
        /// <summary>
        /// 获取用户的购物车列表
        /// </summary>
        Task<List<Cart>> GetCartListAsync(long userId);

        /// <summary>
        /// 添加商品到购物车
        /// </summary>
        Task<bool> AddToCartAsync(long userId, Cart cart);

        /// <summary>
        /// 更新购物车商品数量
        /// </summary>
        Task<bool> UpdateQuantityAsync(long userId, long cartId, Cart cart);

        /// <summary>
        /// 删除购物车商品
        /// </summary>
        Task<bool> DeleteCartItemAsync(long userId, long skuId);

        /// <summary>
        /// 清空购物车
        /// </summary>
        Task<bool> ClearCartAsync(long userId);

        /// <summary>
        /// 获取单个购物车项
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="cartId">购物车项ID</param>
        /// <returns>购物车项</returns>
        Task<Cart> GetCartItemAsync(long userId, long cartId);
    }

    /// <summary>
    /// 购物车服务实现类
    /// 提供购物车的增删改查等功能
    /// </summary>
    public class CartService : ICartService
    {
        private readonly ApplicationDbContext _context;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public CartService(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取用户的购物车列表，包含商品和SKU信息
        /// </summary>
        public async Task<List<Cart>> GetCartListAsync(long userId)
        {
            try 
            {
                // 使用显式的 LEFT JOIN 查询
                var query = from c in _context.Carts
                           join g in _context.Goods 
                           on c.SpuId equals g.SpuId
                           join s in _context.Skus 
                           on c.SkuId equals s.SkuId into gj
                           from s in gj.DefaultIfEmpty()
                           where c.UserId == userId
                           orderby c.CreateTime descending
                           select new Cart
                           {
                               Id = c.Id,
                               UserId = c.UserId,
                               SpuId = c.SpuId,
                               SkuId = c.SkuId,
                               GoodTitle = c.GoodTitle,
                               SalePrice = c.SalePrice,
                               Quantity = c.Quantity,
                               IsSelected = c.IsSelected,
                               SpecValues = c.SpecValues,
                               LinePrice = c.LinePrice,
                               Unit = c.Unit,
                               Code = c.Code,
                               StockQuantity = c.StockQuantity,
                               CreateTime = c.CreateTime,
                               UpdateTime = c.UpdateTime,
                               Good = g,
                               SKU = s
                           };

                var carts = await query.ToListAsync();

                // 过滤购物车项
                return carts.Where(c => 
                {
                    // 首先检查商品是否存在且未删除
                    if (c.Good == null || 
                        (c.Good.IsDeleted.HasValue && c.Good.IsDeleted.Value))
                    {
                        return false;
                    }

                    // 根据商品类型进行不同的处理
                    if (c.Good.OpenSpec == 1)
                    {
                        // 多规格商品：需要检查SKU
                        return c.SKU != null && 
                            (!c.SKU.IsDeleted.HasValue || !c.SKU.IsDeleted.Value);
                    }

                    // 单规格商品：不需要检查SKU
                    return true;
                }).ToList();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取购物车列表失败: {ex.Message}");
                throw new Exception($"获取购物车失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 添加商品到购物车
        /// </summary>
        public async Task<bool> AddToCartAsync(long userId, Cart cart)
        {
            try
            {
                // 添加日志
                Console.WriteLine($"正在添加商品到购物车: SkuId={cart.SkuId}, SpuId={cart.SpuId}");

                // 获取商品信息
                var good = await _context.Goods
                    .FirstOrDefaultAsync(g => g.SpuId == cart.SpuId && 
                        (!g.IsDeleted.HasValue || !g.IsDeleted.Value));

                if (good == null)
                {
                    Console.WriteLine($"商品不存在或已删除: SpuId={cart.SpuId}");
                    throw new Exception("商品不存在或已下架");
                }

                // 如果是多规格商品，验证SKU
                if (good.OpenSpec == 1)
                {
                    var sku = await _context.Skus
                        .FirstOrDefaultAsync(s => s.SkuId == cart.SkuId && 
                            (!s.IsDeleted.HasValue || !s.IsDeleted.Value));

                    if (sku == null)
                    {
                        Console.WriteLine($"SKU不存在或已删除: SkuId={cart.SkuId}");
                        throw new Exception("商品规格不存在或已下架");
                    }

                    // 检查库存
                    if (sku.Stock < cart.Quantity)
                    {
                        throw new Exception("商品库存不足");
                    }
                }
                else
                {
                    // 单规格商品检查库存
                    if (good.SpuStockQuantity < cart.Quantity)
                    {
                        throw new Exception("商品库存不足");
                    }
                }

                // 检查是否已在购物车中
                var existingCart = await _context.Carts
                    .FirstOrDefaultAsync(c => 
                        c.UserId == userId && 
                        c.SkuId == cart.SkuId);

                if (existingCart != null)
                {
                    // 更新现有购物车项
                    existingCart.Quantity += cart.Quantity;
                    existingCart.UpdateTime = DateTime.Now;
                }
                else
                {
                    // 创建新购物车项
                    cart.UserId = userId;
                    cart.IsSelected = true;
                    cart.CreateTime = DateTime.Now;
                    cart.UpdateTime = DateTime.Now;

                    _context.Carts.Add(cart);
                }

                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加购物车失败: {ex.Message}");
                throw new Exception($"添加购物车失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新购物车中商品的数量
        /// </summary>
        public async Task<bool> UpdateQuantityAsync(long userId, long cartId, Cart cart)
        {
            try
            {
                // 先获取购物车项
                var existingCart = await _context.Carts
                    .FirstOrDefaultAsync(c => 
                        c.UserId == userId && 
                        c.Id == cartId);

                if (existingCart == null)
                    throw new Exception("购物车商品不存在");

                // 检查商品是否存在
                var good = await _context.Goods
                    .FirstOrDefaultAsync(g => g.SpuId == existingCart.SpuId && 
                        (!g.IsDeleted.HasValue || !g.IsDeleted.Value));

                if (good == null)
                {
                    throw new Exception("商品不存在或已下架");
                }

                // 判断是否是多规格商品
                if (good.OpenSpec == 1)
                {
                    // 多规格商品：验证SKU
                    var sku = await _context.Skus
                        .FirstOrDefaultAsync(s => s.SkuId == existingCart.SkuId && 
                            (!s.IsDeleted.HasValue || !s.IsDeleted.Value));

                    if (sku == null)
                    {
                        throw new Exception("商品规格不存在或已下架");
                    }

                    // 检查SKU库存
                    if (sku.Stock < cart.Quantity)
                    {
                        throw new Exception("商品库存不足");
                    }
                }
                else
                {
                    // 单规格商品：检查商品库存
                    if (!good.SpuStockQuantity.HasValue || 
                        good.SpuStockQuantity.Value < cart.Quantity)
                    {
                        throw new Exception("商品库存不足");
                    }
                }

                // 更新购物车数量
                existingCart.Quantity = cart.Quantity;
                existingCart.UpdateTime = DateTime.Now;
                await _context.SaveChangesAsync();

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"更新购物车数量失败: {ex.Message}");
                throw new Exception($"更新购物车数量失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 从购物车中删除商品（物理删除）
        /// </summary>
        public async Task<bool> DeleteCartItemAsync(long userId, long skuId)
        {
            try
            {
                var cart = await _context.Carts
                    .FirstOrDefaultAsync(c => 
                        c.UserId == userId && 
                        c.Id == skuId);

                if (cart == null)
                    throw new Exception("购物车商品不存在");

                _context.Carts.Remove(cart);
                return await _context.SaveChangesAsync() > 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除购物车商品失败: {ex.Message}");
                throw new Exception($"删除购物车商品失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 清空购物车
        /// </summary>
        public async Task<bool> ClearCartAsync(long userId)
        {
            try
            {
                // 获取用户的所有购物车项
                var carts = await _context.Carts
                    .Where(c => c.UserId == userId)
                    .ToListAsync();

                // 直接删除所有购物车项
                _context.Carts.RemoveRange(carts);
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"清空购物车失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 获取单个购物车项
        /// </summary>
        public async Task<Cart> GetCartItemAsync(long userId, long cartId)
        {
            try 
            {
                // 使用显式的 LEFT JOIN 查询
                var cart = await (from c in _context.Carts
                                 join g in _context.Goods on c.SpuId equals g.SpuId
                                 join s in _context.Skus on c.SkuId equals s.SkuId into skuGroup
                                 from s in skuGroup.DefaultIfEmpty()
                                 where c.UserId == userId && c.Id == cartId
                                 select new Cart
                                 {
                                     Id = c.Id,
                                     UserId = c.UserId,
                                     SpuId = c.SpuId,
                                     SkuId = c.SkuId,
                                     GoodTitle = c.GoodTitle,
                                     SalePrice = c.SalePrice,
                                     Quantity = c.Quantity,
                                     IsSelected = c.IsSelected,
                                     SpecValues = c.SpecValues,
                                     LinePrice = c.LinePrice,
                                     Unit = c.Unit,
                                     Code = c.Code,
                                     Good = g,
                                     SKU = s
                                 }).FirstOrDefaultAsync();

                if (cart == null)
                {
                    throw new KeyNotFoundException("购物车商品不存在");
                }

                // 确保商品存在且未删除
                if (cart.Good == null || 
                    (cart.Good.IsDeleted.HasValue && cart.Good.IsDeleted.Value))
                {
                    throw new Exception("商品不存在或已下架");
                }

                return cart;
            }
            catch (Exception ex)
            {
                throw new Exception($"获取购物车商品失败: {ex.Message}");
            }
        }
    }
}